package com.jensen.metaq.example;

import com.jensen.metaq.example.util.Help;
import com.taobao.metamorphosis.client.MetaMessageSessionFactory;
import com.taobao.metamorphosis.client.consumer.ConsumerConfig;
import com.taobao.metamorphosis.client.consumer.MessageConsumer;
import com.taobao.metamorphosis.client.producer.MessageProducer;
import com.taobao.metamorphosis.exception.MetaClientException;

/**
 * Created by szhua on 2016/6/8.
 */
//单例模式（双重检查锁定）
public class MessageFactory {

    private static volatile MetaMessageSessionFactory metaMessageSessionFactory=null;
    private static volatile MessageProducer messageProducer=null;
    private static volatile MessageConsumer messageConsumer=null;

    public static MetaMessageSessionFactory getMetaMessageSessionFactoryInstance(){
        if (metaMessageSessionFactory==null){
            synchronized (MetaMessageSessionFactory.class){
                if (metaMessageSessionFactory==null){
                    try {
                        metaMessageSessionFactory=new MetaMessageSessionFactory(Help.initMetaConfig());
                    } catch (MetaClientException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return metaMessageSessionFactory;
    }

    public static MessageProducer getMessageProducerInstance(){
        if (messageProducer==null){
            if (metaMessageSessionFactory==null){
                if (getMetaMessageSessionFactoryInstance()==null) return null;
                else  {
                    synchronized (MessageProducer.class){
                        if (messageProducer==null){
                            messageProducer=metaMessageSessionFactory.createProducer();
                        }
                    }
                }
            }
        }
        return messageProducer;
    }

    public static MessageConsumer getMessageConsumerInstance(){
        if (messageConsumer==null){
            if (metaMessageSessionFactory==null){
                if (getMetaMessageSessionFactoryInstance()==null) return null;
                else {
                    synchronized (MessageConsumer.class){
                        if (messageConsumer==null){
                            messageConsumer=metaMessageSessionFactory.createConsumer(new ConsumerConfig("meta-example"));
                        }
                    }
                }
            }
        }
        return messageConsumer;

    }

}
